﻿using DataModels;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace ScheduledTasks
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddScheduledTasks(this IServiceCollection services)
        {
            var assembly = Assembly.GetExecutingAssembly();

            var taskTypes = assembly.GetTypes()
                .Where(t => typeof(IScheduledTask).IsAssignableFrom(t)
                         && !t.IsInterface
                         && !t.IsAbstract)
                .ToList();

            // 注册为作用域服务
            foreach (var taskType in taskTypes)
            {
                services.AddScoped(typeof(IScheduledTask), taskType);
                Console.WriteLine($"已注册定时任务: {taskType.FullName}");
            }

            // 注册后台服务
            services.AddHostedService<TaskService>();

            return services;
        }
    }
}
